﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class Main_Accounts_VoucherDisplay_Contra_view : System.Web.UI.Page
{
    double grandtotal_dr = 0;
    double grandtotal_cr = 0;
    Datautility du = new Datautility();
    DataTable DTMain = new DataTable();
    string strsql = "";
    string currentyear = "";
    string Nextyear = "";
    string currentFyear = "";

    public int CurrentPage
    {
        get
        {
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt16(ViewState["CurrentPage"].ToString());
            }
        }
        set
        {
            ViewState["CurrentPage"] = value;
        }
    }
    PagedDataSource pds = new PagedDataSource();
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            BindTransaction();
            //**************Set Minimum and maximum date calender Control********
            AccountSettings.setMinMaxDate(form1);
            //********************End **********
            GetFinanceYear();  
        }     
    }
    protected void GetFinanceYear()
    {       
        string FromDate = "01/04/" + Session["FINYEAR"].ToString();
        string ToDate = "31/03/" + (Convert.ToDouble(Session["FINYEAR"]) + 1).ToString();       
        txtfrom.Text = FromDate.ToString();
        txtto.Text = ToDate.ToString();
        BindDataList(FromDate, ToDate);      
    }
    protected void BindDataList(string fromdate, string todate)
    {
        if (DTMain.Rows.Count > 0)
        {
            foreach (DataRow dr in DTMain.Rows)
            {
                dr.Delete();
            }
        }        
        string[] str = fromdate.ToString().Split('/');
        string FromDateMain = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
        string[] str1 = todate.ToString().Split('/');
        string ToDateMain = str1[1].ToString() + "/" + str1[0].ToString() + "/" + str1[2].ToString();
        SqlParameter[] parma ={
                               new SqlParameter("@TransactionTypeID",ddlTransaction.SelectedValue.ToString()), // 1 for Contra
                               new SqlParameter("@FromDate",FromDateMain),
                               new SqlParameter("@todate",ToDateMain)
                              };
        DTMain = du.getdatausingprocedure("USP_ACC_GetVoucherViewDetails", parma);
        if (DTMain.Rows.Count > 0)
        {
           
            DataTable DT = new DataTable();
            string[] columns = { "TransactionId", "TransactionDate", "TransactionNumber", "ChequeNumber", "Narration" };
            DT = DTMain.DefaultView.ToTable(true, columns);
           

                pds.DataSource = DT.DefaultView;
                pds.AllowPaging = true;
                pds.PageSize = 10;
                pds.CurrentPageIndex = CurrentPage;
                dtlcontra.DataSource = pds;
                dtlcontra.DataBind();
                DoPaging();
                lblRecord.Text = "Displaying " + ((pds.CurrentPageIndex * pds.PageSize) + 1).ToString() + " To " + (pds.Count < pds.PageSize ? (pds.CurrentPageIndex == 0 ? pds.Count : pds.PageSize + pds.Count) : ((pds.CurrentPageIndex * pds.PageSize) + pds.PageSize)).ToString() + " Of " + DT.Rows.Count.ToString() + " Vouchers";
                //lblRecord.Text = Convert.ToString((pds.PageSize * pds.CurrentPageIndex) + (pds.PageSize) + ((DT.Rows.Count - pds.PageSize) * pds.CurrentPageIndex));
                // lblRecord.Text = "Displaying  " + ((pds.PageSize * pds.CurrentPageIndex) + 1) + "  To  " +
                //((pds.PageSize) + ((DT.Rows.Count - pds.PageSize) * pds.CurrentPageIndex)) + " of  " + DT.Rows.Count.ToString() + "   Vouchers  ";
                pnlcontra.Visible = true;
                pnlpaging.Visible = true;
            }
            else
            {
                //dtlcontra.DataSource = DTMain;
                //dtlcontra.DataBind();
                //pnlcontra.Visible = true;
                //pnlpaging.Visible = true;

                DoPaging();
                lblMsg.Text = "No Record Found!";
                lblMsg.Attributes.Add("class", "false");
                pnlcontra.Visible = false;
                pnlpaging.Visible = false;
               
            }
    }
    private void DoPaging()
    {
        DataTable DT = new DataTable();
        DT.Columns.Add("PageIndex");
        DT.Columns.Add("PageText");
        for (int i = 0; i < pds.PageCount; i++)
        {
            DataRow DR = DT.NewRow();
            DR[0] = i;
            DR[1] = i + 1;
            DT.Rows.Add(DR);
        }
        DLPaging.DataSource = DT;
        DLPaging.DataBind();
    }
    protected void BindTransaction()
    {
        SqlParameter[] sqlpara = {
                                         new SqlParameter("@ParentTypeID","1"), //1 for contra
                                         new SqlParameter("@ModuleType","1") //1 for accounts
                                     };

        DataTable DTTran = du.getdatausingprocedure("USP_Get_Transaction_By_ParentTypeID", sqlpara);
        if (DTTran.Rows.Count > 0)
        {
            ddlTransaction.DataSource = DTTran;
            ddlTransaction.DataTextField = "TRANSACTIONNAME";
            ddlTransaction.DataValueField = "TYPEID";
            ddlTransaction.SelectedValue = "1";
            ddlTransaction.DataBind();
        }
    }
    protected void dtlcontra_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        grandtotal_dr = 0;
        grandtotal_cr = 0;
        
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {

            Literal ltrcheque_no = (Literal)e.Item.FindControl("ltrcheque_no");
            Literal ltrnarration = (Literal)e.Item.FindControl("ltrnarration");
            Literal ltrcheque_name = (Literal)e.Item.FindControl("ltrcheque_name");
            Literal ltrnarration_name = (Literal)e.Item.FindControl("ltrnarration_name");
            HiddenField htrans_id = (HiddenField)e.Item.FindControl("htrans_id");
            GridView gridContra = (GridView)e.Item.FindControl("gridContra");

            HyperLink hyperEdit = (HyperLink)e.Item.FindControl("hyperEdit");
           // hyperEdit.NavigateUrl = "../VoucherEntry/Contra.aspx?TranId=" + htrans_id.Value; ;


            DataTable DT = (DataTable)DTMain;
            
            SqlParameter[] paraa = { 
                                   new SqlParameter("@tranid",htrans_id.Value.ToString())
                                   };
            DataTable dtTransactionTypeID = du.getdatausingprocedure("usp_get_transactiontype", paraa);
            if (dtTransactionTypeID.Rows.Count > 0)
            {
                if (dtTransactionTypeID.Rows[0]["typeid"].ToString() != string.Empty)
                {
                    string from = "";
                    string to = "";
                    string[] d1 = txtfrom.Text.ToString().Split('/');
                    from = d1[1].ToString() + "/" + d1[0].ToString() + "/" + d1[2].ToString();
                    string[] d2 = txtto.Text.ToString().Split('/');
                    to = d2[1].ToString() + "/" + d2[0].ToString() + "/" + d2[2].ToString();


                    HyperLink hyp_print = (HyperLink)e.Item.FindControl("hyp_print");
                    hyp_print.Attributes.Add("onclick", "go('" + htrans_id.Value.ToString() + "','" + from + "','" + to + "','" + dtTransactionTypeID.Rows[0]["typeid"].ToString() + "');");
                }
            }
            if (DT.Rows.Count > 0)
            {
                DataView DView = DT.DefaultView;
                DView.RowFilter = "TransactionID='" + htrans_id.Value + "'";
                DataTable DT1 = DView.ToTable();
                gridContra.DataSource = DT1;
                gridContra.DataBind();
            }
            else
            {
                gridContra.DataSource = DT;
                gridContra.DataBind();
            }
        }
    }
    protected void gridContra_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView grdBind = (GridView)sender;
        DataListItem dlItem = (DataListItem)grdBind.Parent;
       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Literal debit = (Literal)e.Row.Cells[1].FindControl("ltrdebit");
            Literal credit = (Literal)e.Row.Cells[1].FindControl("ltrcredit");
           
            string dk = grdBind.DataKeys[e.Row.RowIndex].Value.ToString();
            strsql = "select amount from acc_voudetails where vouserial='" + dk.ToString() + "'";
            DataTable DT = du.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                if (DT.Rows[0]["amount"].ToString() != string.Empty)
                { 
                    Literal dr = (Literal)e.Row.Cells[1].FindControl("ltrdr_cr");
                if (Convert.ToDouble(DT.Rows[0]["amount"].ToString()) > 0)
                {
                    dr.Text = "Cr";
                }
                else
                {
                    dr.Text = "Dr";
                }

                }
                
            }
            if (Convert.ToDouble(debit.Text) == 0)
            {
                debit.Text = "";
            }
            else
            {
                debit.Text = Math.Abs(Convert.ToDouble(debit.Text)).ToString("N2");
                grandtotal_dr += Convert.ToDouble(debit.Text);
            }
            if (Convert.ToDouble(credit.Text) == 0)
            {
                credit.Text = "";
            }
            else
            {
               credit.Text= Math.Abs(Convert.ToDouble(credit.Text)).ToString("N2");
               grandtotal_cr += Convert.ToDouble(credit.Text);
            }
            
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            ((Literal)e.Row.FindControl("ltrtotdr")).Text = grandtotal_dr.ToString("N2");
            ((Literal)e.Row.FindControl("ltrtotcr")).Text = grandtotal_cr.ToString("N2");
            e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
            e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;
        }
    }
    protected void btnSearch_period_Click(object sender, EventArgs e)
    {
        BindDataList(txtfrom.Text.ToString(), txtto.Text.ToString());
        pnlcontra.Visible = true;
        pnlpaging.Visible = true;
    }
    protected void dtlcontra_ItemCommand(object source, DataListCommandEventArgs e)
    {
        //if (e.CommandName == "print")
        //{
        //    string key = e.CommandArgument.ToString();
        //    Response.Write("<script type='text/javascript' language='javascript'>");
        //    //Response.Write("{");
        //    Response.Write("window.open('../VoucherPrint/Contra_print.aspx?key=" + key + "');");
        //    //Response.Write("}");
        //    Response.Write("</script>");
        //}
    }
    protected void DLPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Paging"))
        {
            string FromDate = "01/04/" + Session["FINYEAR"].ToString();
            string ToDate = "31/03/" + (Convert.ToDouble(Session["FINYEAR"]) + 1).ToString();
            txtfrom.Text = FromDate.ToString();
            txtto.Text = ToDate.ToString();
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            BindDataList(FromDate, ToDate);
        }
    }
    protected void DLPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("LnkBtnPaging");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Font.Bold = true;
            lnkbtnPage.BackColor = System.Drawing.ColorTranslator.FromHtml("#d1d1d1");
            lnkbtnPage.ForeColor = System.Drawing.Color.White;
             
        }
    }
    protected void searchvoucher(string fromdate, string todate)
    {
        string[] str = fromdate.ToString().Split('/');
        string FromDateMain = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
        string[] str1 = todate.ToString().Split('/');
        string ToDateMain = str1[1].ToString() + "/" + str1[0].ToString() + "/" + str1[2].ToString();
        SqlParameter[] parma ={
                               new SqlParameter("@TransactionTypeID","1"), // 1 for Contra
                               new SqlParameter("@FromDate",FromDateMain),
                               new SqlParameter("@todate",ToDateMain)
                              };
        DTMain = du.getdatausingprocedure("USP_ACC_GetVoucherViewDetails", parma);
        if (DTMain.Rows.Count > 0)
        {
            DataTable DT = new DataTable();
            DataView dv = DTMain.DefaultView;
            dv.RowFilter = "TransactionNumber='" + TxtvoucherNo.Text.Trim() + "'";
            string[] columns = { "TransactionId", "TransactionDate", "TransactionNumber", "ChequeNumber", "Narration" };
            DT = dv.ToTable(true, columns);
            if (DT.Rows.Count > 0)
            {
                pds.DataSource = DT.DefaultView;
                pds.AllowPaging = true;
                pds.PageSize = 10;
                pds.CurrentPageIndex = CurrentPage;
                dtlcontra.DataSource = DT;
                dtlcontra.DataBind();
                dtlcontra.DataSource = pds;
                dtlcontra.DataBind();
                DoPaging();
                lblRecord.Text = "Displaying " + ((pds.CurrentPageIndex * pds.PageSize) + 1).ToString() + " To " + (pds.Count < pds.PageSize ? (pds.CurrentPageIndex == 0 ? pds.Count : pds.PageSize + pds.Count) : ((pds.CurrentPageIndex * pds.PageSize) + pds.PageSize)).ToString() + " Of " + DT.Rows.Count.ToString() + " Vouchers";
                //dtlcontra.DataSource = dv.ToTable(true, columns);
                //dtlcontra.DataBind();
                pnlcontra.Visible = true;
                pnlpaging.Visible = true;
            }
            else
            {
                dtlcontra.DataBind();
                DoPaging();
                lblMsg.Text = "No Record Found!";
                lblMsg.Attributes.Add("class", "false");
                pnlcontra.Visible = false;
                pnlpaging.Visible = false;
                   
            }
        }
    }
    protected void BtnSearch_Click(object sender, EventArgs e)
    {
        if (TxtvoucherNo.Text != string.Empty)
        {
            string FromDate = "01/04/" + Session["FINYEAR"].ToString();
            string ToDate = "31/03/" + (Convert.ToDouble(Session["FINYEAR"]) + 1).ToString();
            txtfrom.Text = FromDate.ToString();
            txtto.Text = ToDate.ToString();
            searchvoucher(FromDate, ToDate);
        }
        else
        {
            lblMsg.Text = "Enter Voucher Number!";
            lblMsg.Attributes.Add("class", "false");
        }
    }
    protected void ddlTransaction_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (txtfrom.Text != string.Empty && txtto.Text != string.Empty)
        {
            BindDataList(txtfrom.Text, txtto.Text);
        }
    }
}
